"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 系统内部使用工具
Case Name   : 数据库集群状态为Degraded时进行减容，减容失败
Create At   : 2022/04/11
Owner       : opentestcase023
Description :
    1.构造集群状态Degraded
    2.gs_dropnode进行减容：
    ./gs_dropnode -U {usrname} -G {grp_name} -h {hostname}
    3.清理环境
    启动数据库恢复环境
Expect      :
    1.集群Degraded状态构造成功
    2.备机减容失败
    3.环境恢复成功
History     :
    2022-5-17 opentestcase023 优化用例，根据自动化连跑要求，修改用例为在源库上减容
"""
import os
import unittest
from testcase.utils.Common import Common
from testcase.utils.Common import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger
from yat.test import Node
from yat.test import macro
primary_sh = CommonSH('PrimaryDbUser')
Constant = Constant()


@unittest.skipIf(3 != primary_sh.get_node_num(), '非1+2环境不执行')
class Tools(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.common = Common()
        self.log.info(f'----{os.path.basename(__file__)} start----')
        self.primary_root_node = Node('PrimaryRoot')
        self.primary_node = Node('PrimaryDbUser')
        self.standby1_root_node = Node('Standby1Root')
        self.standby2_root_node = Node('Standby2Root')
        self.u_name = self.primary_node.ssh_user
        num = primary_sh.get_node_num()
        self.assertGreaterEqual(num, 3, "执行失败:节点数量异常，减容不执行")
        self.hosts_bac_flag = 1
        self.log.info('备份hosts文件')
        self.primary_root_node.sh(f'cp /etc/hosts /etc/hostsbac')
        self.check_res = self.primary_root_node.sh(f'cat /etc/hosts').result()
        check_bac_res = self.primary_root_node.sh(f'cat /etc/hostsbac').result()
        self.assertEqual(self.check_res, check_bac_res, 'hosts文件备份失败')
        self.hosts_bac_flag = 2

    def test_gs_dropnode(self):
        text = '----step1:构建数据库Degrade状态 expect:成功----'
        self.log.info(text)
        add_cmd = f"echo -e {self.primary_node.ssh_host} > /etc/hosts;" \
                  f"cat /etc/hosts;"
        self.log.info(add_cmd)
        add_res = self.primary_root_node.sh(add_cmd).result()
        self.log.info(add_res)
        self.assertEqual(add_res, self.primary_node.ssh_host, '主机ip写入失败')
        check_cmd = f'source {macro.DB_ENV_PATH};' \
                    f'gs_om -t status --detail;'
        self.log.info(check_cmd)
        check_res = self.primary_node.sh(check_cmd).result()
        self.assertIn('Degrade', check_res, text + '构造集群Degrade状态失败')

        text = '----step2:执行gs_dropnode进行备机减容 expect:失败'
        self.log.info(text)
        text = '----查看主机名----'
        self.log.info(text)
        standby2_node_name = self.standby2_root_node.sh("uname -n").result()
        self.log.info(standby2_node_name)
        self.assertIsNotNone(standby2_node_name, '执行失败:' + text)

        drop_cmd = f'gs_dropnode -U {self.u_name} -G {self.u_name} ' \
                   f'-h {self.standby1_root_node.ssh_host}'
        self.log.info(drop_cmd)
        global shell_path
        shell_path = os.path.join('/', 'home', f'{self.u_name}', 'dropnode.sh')
        shell_cmd = f'touch {shell_path};echo -e {drop_cmd} > {shell_path};' \
                    f'chmod 755 {shell_path};cat {shell_path}'
        self.log.info(shell_cmd)
        shell_res = self.primary_root_node.sh(shell_cmd).result()
        self.log.info(shell_res)
        execute_cmd = f'source {macro.DB_ENV_PATH};' \
                      f'{shell_path};'
        self.log.info(execute_cmd)
        drop_res = self.primary_node.sh(execute_cmd).result()
        self.log.info(drop_res)
        check_msg = f"[GAUSS-35807] The host {standby2_node_name} which " \
                    f"still exist in the cluster can't be connected"
        self.assertIn(check_msg, drop_res, text + '执行失败')

    def tearDown(self):
        text = "----step3:恢复hosts、启动数据库、恢复环境 expect:成功----"
        self.log.info(text)
        self.log.info('----恢复hosts文件----')
        if self.hosts_bac_flag == 1:
            exe_cmd = f'rm -rf /etc/hostsbac'
            self.log.info(exe_cmd)
        else:
            exe_cmd = f'rm -rf /etc/hosts;mv /etc/hostsbac /etc/hosts;' \
                      f'chmod 755 /etc/hosts;cat /etc/hosts'
            self.log.info(exe_cmd)
        res = self.primary_root_node.sh(exe_cmd).result()
        self.log.info(res)
        start_cmd = f'source {macro.DB_ENV_PATH};' \
                    f'gs_om -t start;' \
                    f'gs_om -t status --detail;'
        self.log.info(start_cmd)
        check_res = self.primary_node.sh(start_cmd).result()
        self.log.info(check_res)
        del_cmd = f"rm -rf {shell_path}"
        self.log.info(del_cmd)
        del_res = self.primary_root_node.sh(del_cmd).result()
        self.log.info(del_res)
        self.assertEqual('', del_res, '文件删除失败')
        self.assertEqual(res, self.check_res, '恢复hosts文件失败')
        self.assertIn('Successfully started', check_res, '数据库启动失败')
        self.log.info(f'----{os.path.basename(__file__)} finish----')
